package com.zitronella.course.osseventmanager.service;

import com.zitronella.course.osseventmanager.domain.Event;
import com.zitronella.course.osseventmanager.domain.Position;
import com.zitronella.course.osseventmanager.domain.EventUser;

import javax.persistence.*;

import java.util.List;
import java.util.Date;

import org.springframework.orm.jpa.support.JpaDaoSupport;
import org.springframework.orm.jpa.JpaCallback;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;


/**
 * Created by IntelliJ IDEA.
 * User: Robin
 * Date: Feb 19, 2009
 * Time: 10:32:57 AM
 * To change this template use File | Settings | File Templates.
 */
public class EventServiceImpl extends JpaDaoSupport implements EventService{

    /**
     *A1
     * @param newEvent
     */
    public void createEvent(Event newEvent) {
        getJpaTemplate().persist(newEvent);
    }

    /**
     *  A5
     * @param newEvent
     */
    public boolean removeEvent(Event newEvent){
        newEvent = getJpaTemplate().merge(newEvent);
        getJpaTemplate().remove(newEvent);
        return true;
    }

    public Event findEvent(Long id) {
        return getJpaTemplate().find(Event.class, id);
    }

    public Event findEventByName(String name) {
        List list = getJpaTemplate().find("select e from Event e where e.name = ?1", name);
        System.out.println("Size is "+list.size());
       return (Event) list.get(0);
    }

    /**
     *  A3 Part 1
     * @param e
     */
    public void updateEvent(Event e){

        e = getJpaTemplate().merge(e);
        getJpaTemplate().persist(e);
    }

    public List<Event> findEventByAdministratorEmail(String emailID){
        final String emailId = emailID;
        return (List<Event>) getJpaTemplate().executeFind(new JpaCallback() {
            public Object doInJpa(EntityManager entityManager) throws PersistenceException {
                Query q = entityManager.createQuery("from Event where adminUserAccountId = ? ");
                q.setParameter(1, emailId);
                return q.getResultList();
            }
        });
    }

    // method to find future events from a start date V1
    @SuppressWarnings("unchecked")
    public List<Event> findFutureEvents(Date startDate) {
        final Date date = startDate;
        return (List<Event>) getJpaTemplate().executeFind(new JpaCallback() {
            public Object doInJpa(EntityManager entityManager) throws PersistenceException {
                Query q = entityManager.createQuery("from Event where startDate > :time");
                q.setParameter("time", date);
                return q.getResultList();
            }
        });
    }
}